package com.wsj.util.tool;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.tree.DefaultElement;

import com.wsj.vo.homeSiteXml.ItemVo;

 

/**

 * @author Holen Chen

 */

public class Dom4jDemo {

	

    public Dom4jDemo() {

    }

    

    /**

     * 建立一个XML文档,文档名由输入参数决定

     * @param filename 需建立的文件名

     * @return 返回操作结果, 0表失败, 1表成功

     */

    public int createXMLFile(String filename){

       /** 返回操作结果, 0表失败, 1表成功 */

       int returnValue = 0;

       /** 建立document对象 */

        Document document = DocumentHelper.createDocument();

       /** 建立XML文档的根books */

        Element booksElement = document.addElement("books");

       /** 加入一行注释 */

        booksElement.addComment("This is a test for dom4j, holen, 2004.9.11");

       /** 加入第一个book节点 */

        Element bookElement = booksElement.addElement("book");

       /** 加入show参数内容 */

        bookElement.addAttribute("show","yes");

       /** 加入title节点 */

        Element titleElement = bookElement.addElement("title");

       /** 为title设置内容 */

        titleElement.setText("Dom4j Tutorials");

       

       /** 类似的完成后两个book */

        bookElement = booksElement.addElement("book");

        bookElement.addAttribute("show","yes");

        titleElement = bookElement.addElement("title");

        titleElement.setText("Lucene Studing");

        bookElement = booksElement.addElement("book");

        bookElement.addAttribute("show","no");

        titleElement = bookElement.addElement("title");

        titleElement.setText("Lucene in Action");

       

       /** 加入owner节点 */

        Element ownerElement = booksElement.addElement("owner");

        ownerElement.setText("O'Reilly");

       

       try{

           /** 将document中的内容写入文件中 */

           XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)));

           writer.write(document);

           writer.close();

           /** 执行成功,需返回1 */

           returnValue = 1;

        }catch(Exception ex){

           ex.printStackTrace();

       }

               

        return returnValue;

    }

    

    /**

     * 修改XML文件中内容,并另存为一个新文件

     * 重点掌握dom4j中如何添加节点,修改节点,删除节点

     * @param filename 修改对象文件

     * @param newfilename 修改后另存为该文件

     * @return 返回操作结果, 0表失败, 1表成功

     */

    public static int ModiXMLFile(String filename,String newfilename,ItemVo itemvo){

        int returnValue = 0;

        try{

            SAXReader saxReader = new SAXReader();    

            Document document = saxReader.read(new File(filename));

            /** 修改内容之三: 若title内容为Dom4j Tutorials,则删除该节点 */

            List  list = document.selectNodes("/bcaster/item/@id");
            Iterator iter = list.iterator();
            int length=0;
            while(iter.hasNext()){
                Attribute attribute = (Attribute)iter.next();
                if(attribute.getValue().equals(itemvo.getId()))
                {
             	   length=attribute.getParent().attributes().size();
             	   if(length>2){
       				attribute.getParent().attribute(0).setValue(itemvo.getItem_url());
       				attribute.getParent().attribute(1).setValue(itemvo.getLink());
       				attribute.getParent().attribute(2).setValue(itemvo.getId()); 
             	   }else
             	   {
                      document.getRootElement().remove(attribute.getParent());
                      Element emp1Element = DocumentHelper.createElement("item"); 
                      emp1Element.addAttribute("item_url", itemvo.getItem_url()); 
                      emp1Element.addAttribute("link", itemvo.getLink()); 
                      emp1Element.addAttribute("id", itemvo.getId()); 
                      emp1Element.addAttribute("titleName", itemvo.getTitleName()); 
                      document.getRootElement().add(emp1Element); 
             	   }
                }   

            }     

            try{

                /** 将document中的内容写入文件中 */

                XMLWriter writer = new XMLWriter(new FileWriter(new File(newfilename)));

                writer.write(document);

                writer.close();

                /** 执行成功,需返回1 */
    			Dom4jDemo.formatXMLFile(newfilename);

                returnValue = 1;

            }catch(Exception ex){

                ex.printStackTrace();

            }

            

         }catch(Exception ex){

            ex.printStackTrace();

        }

         return returnValue;

     }
    
    
    /******
     * 更新xml文件中的属性
     * @param filename
     * @param newfilename
     * @param itemvo
     * @return
     * xml文件 ,节点位置 使用xPath比如://book[@type='society'],节点名称, 节点新值
     * @return 返回操作结果, 0表失败, 1表成功
     */
    public static int updateXMLFileAttribute(String filePathAndName,String newfilePathAndName,String noteXPath,String[] attributeName,String[] attributeValue)
    {
    	   try {
			   SAXReader saxReader = new SAXReader(); 
			   Document document = saxReader.read(new File(filePathAndName));
			   
			   //获取节点位置
			   Element noteElement=(Element)document.selectSingleNode(noteXPath);
			   
			   if(attributeName!=null  && attributeValue!=null && attributeName.length == attributeValue.length)
			   {
				    for(int j=0;j<attributeName.length;j++)
				    {
				    	   Attribute attribute = noteElement.attribute(attributeName[j]);
						   //System.out.print("属性名:"+attribute.getName()+"  属性值:"+attribute.getValue());
						   //移除属性
						   if(attribute!=null)
						   {
							   noteElement.remove(attribute);
							   noteElement.addAttribute(attributeName[j], attributeValue[j]);
						   }
				    }
				   
			   }
			   
			   /** 将document中的内容写入文件中 */

               XMLWriter writer = new XMLWriter(new FileOutputStream(new File(newfilePathAndName)));

               writer.write(document);

               writer.close();

               /** 执行成功,需返回1 */
   			  Dom4jDemo.formatXMLFile(newfilePathAndName);
   			  
   			  return 1;

			   
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return 0;
    }
    
    
    
    
    public static int deleteXMLFile(String filename,String newfilename,ItemVo itemvo){
    	
    	int returnValue = 0;
    	
    	try{
    		
    		SAXReader saxReader = new SAXReader();    
    		
    		Document document = saxReader.read(new File(filename));
    		
    		/** 修改内容之三: 若title内容为Dom4j Tutorials,则删除该节点 */
    		
    		List  list = document.selectNodes("/bcaster/item/@id");
    		Iterator iter = list.iterator();
    		while(iter.hasNext()){
    			Attribute attribute = (Attribute)iter.next();
    			if(attribute.getValue().equals(itemvo.getId())){
    				document.getRootElement().remove(attribute.getParent());
    			}   
    			
    		}     
    		try{
    			
    			/** 将document中的内容写入文件中 */
    			
    			XMLWriter writer = new XMLWriter(new FileWriter(new File(newfilename)));
    			
    			writer.write(document);
    			
    			writer.close();
    			
    			/** 执行成功,需返回1 */
    			Dom4jDemo.formatXMLFile(filename);
    			
    			returnValue = 1;
    			
    		}catch(Exception ex){
    			
    			ex.printStackTrace();
    			
    		}
    		
    		
    		
    	}catch(Exception ex){
    		
    		ex.printStackTrace();
    		
    	}
    	
    	return returnValue;
    	
    }
    public static int addXMLFile(String filename,String newfilename,ItemVo itemvo){
    	
    	int returnValue = 0;
    	
    	try{
    		
    		SAXReader saxReader = new SAXReader();    
    		
    		Document document = saxReader.read(new File(filename));
    		    
    		// 添加员工节点 "employee" 
    		Element emp1Element = DocumentHelper.createElement("item"); 
    		emp1Element.addAttribute("item_url", itemvo.getItem_url()); 
    		emp1Element.addAttribute("link", itemvo.getLink()); 
    		emp1Element.addAttribute("id", itemvo.getId()); 
    		emp1Element.addAttribute("titleName", itemvo.getTitleName()); 
    		document.getRootElement().add(emp1Element); 
    		
    		try{
    			
    			/** 将document中的内容写入文件中 */
    			XMLWriter writer = new XMLWriter( new FileOutputStream(new File(newfilename)));
    			
    			writer.write(document);
    			
    			writer.close();
    			
    			/** 执行成功,需返回1 */
    			Dom4jDemo.formatXMLFile(filename);
    			
    			returnValue = 1;
    			
    		}catch(Exception ex){
    			
    			ex.printStackTrace();
    			
    		}
    		
    		
    		
    	}catch(Exception ex){
    		
    		ex.printStackTrace();
    		
    	}
    	
    	return returnValue;
    	
    }
    public static List loadItemList(String filename){
    	
    	List list=new ArrayList();
    	
    	try{
    		
    		SAXReader saxReader = new SAXReader();    
    		
    		Document document = saxReader.read(new File(filename));
    		
    		List xmllist= document.selectNodes("/bcaster/item"); 
    	     for (int i = 0, n = xmllist.size(); i < n; i++) 

    	     { 
    	    	 ItemVo itemvo=new ItemVo();

    	         DefaultElement itemElement = (DefaultElement) xmllist.get(i); 
    	         String item_url = itemElement.attributeValue("item_url"); 
    	         String link = itemElement.attributeValue("link"); 
    	         String id = itemElement.attributeValue("id"); 
    	         String titleName = itemElement.attributeValue("titleName"); 
    	         
    	         itemvo.setId(id);
    	         itemvo.setItem_url(item_url);
    	         itemvo.setLink(link);
    	         itemvo.setTitleName(titleName);
    	         list.add(itemvo);

//    	         System.out.println(item_url + "===========" + link); 

    	     } 

    		
    	}catch(Exception ex){
    		
    		ex.printStackTrace();
    		
    	}
    	
    	return list;
    	
    }

    

    /**

     * 格式化XML文档,并解决中文问题

     * @param filename

     * @return

     */

    public static int formatXMLFile(String filename){

       int returnValue = 0;

       try{

           SAXReader saxReader = new SAXReader();    

           Document document = saxReader.read(new File(filename));

           XMLWriter output = null;

           /** 格式化输出,类型IE浏览一样 */

           OutputFormat format = OutputFormat.createPrettyPrint();

           /** 指定XML字符集编码 */

           format.setEncoding("GBK");

           output = new XMLWriter(new FileWriter(new File(filename)),format);

           output.write(document);

           output.close();        

           /** 执行成功,需返回1 */

           returnValue = 1;       

        }catch(Exception ex){

           ex.printStackTrace();

       }

        return returnValue;

    }



 

//    public static void main(String[] args) {
//
//        Dom4jDemo temp = new Dom4jDemo();
//
//        System.out.println(temp.ModiXMLFile("C://mtf/workspace/qqddc/WebRoot/js/homeSite_pic.xml","d://holen2.xml"));
//
//        System.out.println(temp.formatXMLFile("d://holen2.xml"));
//        
//        System.out.println(temp.loadItemList("C://mtf/workspace/qqddc/WebRoot/js/homeSite_pic.xml"));
//
//    }

}
